// src/modules/admin/controllers/login/controller.js
import { console } from "inspector";
import { AuthService } from "../../../services/auth.service.js";
// import { CaptchaService } from '../../../services/captcha.service.js';
import { userService } from "../../../services/user.service.js";
import { BadRequestError, UnauthorizedError } from "../../../utils/errors.js";
import { db } from "./../../../config/sequelize.js";

const authService = new AuthService(db);

// 定义角色权限等级
const ROLES_HIERARCHY = {
  user: 1,
  editor: 2,
  admin: 3,
  superadmin: 4,
};

export class AuthController {
  /**
   * 管理员登录
   */
  static async login(req, res) {
    const { username, password, captcha } = req.validatedData;

    // 验证验证码 (实际项目中应从session/redis获取)
    // if (req.session.captcha !== captcha) {
    //   throw new BadRequestError('验证码错误');
    // }

    // 验证用户权限
    const user = await authService.authenticate(username, password);
    console.log(user);
    if (!user || ROLES_HIERARCHY[user.role] < ROLES_HIERARCHY.admin) {
      throw new UnauthorizedError("用户名或密码错误，或权限不足");
    }
    // 生成token
    const tokens = await authService.generateTokens({
      id: user.id,
      username: user.username,
      role: user.role,
    });
    res.json({
      code: 200,
      message: "登录成功",
      success: true,
      data: {
        user: {
          id: user.id,
          username: user.username,
          role: user.role,
          avatar: user.avatar,
        },
        ...tokens,
      },
    });
  }

  /**
   * 刷新token
   */
  static async refreshToken(req, res) {
    console.log("开始刷新token");
    const { refreshToken } = req.validatedData;
    console.log("刷新token", refreshToken);
    if (!refreshToken) throw new BadRequestError("请提供刷新令牌");
    const tokens = await authService.refreshAccessToken(refreshToken);

    res.json({
      code: 200,
      message: "刷新成功",
      success: true,
      data: { data: tokens },
    });
  }

  /**
   * 退出登录
   */
  static async logout(req, res) {
    await authService.revokeToken(req.user.id, req.token);

    res.json({
      code: 200,
      success: true,
      message: "退出登录成功",
    });
  }

  static async getAuthenticatedUser(req, res) {
    // 通过中间件后，说明权限已校验
    res.json({
      code: 200,
      valid: true,
      data: {
        user: req.user, // 来自中间件附加的数据
        permissions: [],
      },
    });
  }

  /**
   * 用户注册
   */
  static async registers(req, res) {
    try {
      const { username, password, email, phone, captcha } = req.body;
      // 验证验证码,暂时跳过验证
      // await CaptchaService.verifyCaptcha(phone, captcha, 'register');

      // 检查用户是否存在
      const exists = await userService.checkUserExists(username, email, phone);

      if (exists) {
        throw new UnauthorizedError("该用户名已存在，请更换！");
      }
      // 创建用户
      const user = await userService.createUser({
        username,
        password,
        email,
        phone,
      });

      // 生成访问令牌
      const tokens = await authService.generateTokens({
        id: user.id,
        username: user.username,
      });
      res.json({
        code: 200,
        data: {
          success: true,
          message: "用户注册成功",
          user: {
            id: user.id,
            username: user.username,
            email: user.email,
            phone: user.phone,
          },
          ...tokens,
        },
      });
    } catch (error) {
      console.log("错误信息：", error);
      throw new UnauthorizedError(error.message);
    }
  }

  /**
   * 发送注册验证码
   */
  static async sendRegisterCaptcha(req, res) {
    try {
      const { phone } = req.body;

      // 生成并发送验证码
      await CaptchaService.sendCaptcha(phone, "register");

      res.json({
        code: 200,
        message: "验证码发送成功",
        data: {
          expiresIn: 300, // 5分钟有效期
        },
      });
    } catch (error) {
      throw new UnauthorizedError(error.message);
    }
  }

  /**
   * 验证邮箱
   */
  static async verifyEmail(req, res) {
    try {
      const { code } = req.body;
      const userId = req.user.userId;

      await userService.verifyEmail(userId, code);

      res.json({
        code: 200,
        message: "邮箱验证成功",
      });
    } catch (error) {
      throw new UnauthorizedError(error.message);
    }
  }
}
